/*
 * This file is part of Advanced ABX
 *
 * Copyright 2010 Christian Uebber
 *
 * Advanced ABX is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2, as
 * published by the Free Software Foundation.
 *
 * Advanced ABX is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Advanced ABX.  If not, see <http://www.gnu.org/licenses/>.
 */
package de.uebber.sound.abx.controller;

import de.uebber.sound.abx.model.ABXBean;
import de.uebber.sound.abx.model.ABXDecision;
import de.uebber.sound.lib.SwitchableArrayClip;

import javax.sound.sampled.AudioSystem;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Random;

/**
 * Simple application controller. A view communicates events either by
 * changing bound methods in the application's UI bean or by calling the
 * appropriate methods directly.
 *
 * @author Christian Uebber
 */
public class ABXController implements PropertyChangeListener {

    private static final int A = 0, B = 1;
    private int X;

    private ABXBean bean;
    private SwitchableArrayClip clip = new SwitchableArrayClip();

    private ABXProcessor processor;

    public ABXController() {
        bean = new ABXBean();
        bean.addPropertyChangeListener(this);
        flipX();
    }

    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        if (evt.getPropertyName().equals("fileA")) {
            if (bean.getFileB() != null) {
                bean.setReadyForReading(true);
            }
        }
        if (evt.getPropertyName().equals("fileB")) {
            if (bean.getFileA() != null) {
                bean.setReadyForReading(true);
            }
        }
        if (evt.getPropertyName().equals("transitionLength")) {
            if (clip != null && clip.isOpen()) {
                clip.setTransitionLength(clip.microsecondsToFrames(bean.getTransitionLength() * 1000));
            }
        }
    }

    public void readFiles() {
        try {
            clip.open(AudioSystem.getAudioInputStream(bean.getFileA()));
            clip.addStreams(AudioSystem.getAudioInputStream(bean.getFileB()));
            bean.setTrackMillisecondLength((int) (clip.getMicrosecondLength() / 1000));
            bean.setReadyForPlayback(true);
            bean.setReadyForTesting(true);
            clip.setTransitionLength(clip.microsecondsToFrames(bean.getTransitionLength() * 1000));
        } catch (Exception e) {
            bean.publish("Error reading files!");
            bean.publish(e.getMessage());
            bean.setReadyForPlayback(false);
            bean.setReadyForTesting(false);
        }
    }

    public void switchToA() {
        if (clip.isOpen())
            clip.switchStream(A);
    }

    public void switchToB() {
        if (clip.isOpen())
            clip.switchStream(B);
    }

    public void switchToX() {
        if (clip.isOpen())
            clip.switchStream(X);
    }

    public void decideXisA() {
        if (bean.isModifiable())
            beginTest();
        if (X == A) {
            if (!processor.processDecision(new ABXDecision(true)))
                bean.setReadyForTesting(false);
        } else {
            if (!processor.processDecision(new ABXDecision(false)))
                bean.setReadyForTesting(false);
        }
        flipX();
    }

    public void decideXisB() {
        if (bean.isModifiable())
            beginTest();
        if (X == B) {
            if (!processor.processDecision(new ABXDecision(true)))
                bean.setReadyForTesting(false);
        } else {
            if (!processor.processDecision(new ABXDecision(false)))
                bean.setReadyForTesting(false);
        }
        flipX();
    }

    private void flipX() {
        X = new Random().nextBoolean() ? A : B;
    }

    public void beginTest() {
        bean.setModifiable(false);
        clip.setTransitionLength(clip.microsecondsToFrames(bean.getTransitionLength() * 1000));
        processor = new ABXProcessor(bean.getNumberOfRounds(), bean);
        bean.publish("Advanced ABX");
        bean.publish("");
        bean.publish("Copyright 2010 Christian Uebber");
        bean.publish("");
        bean.publish("File A: " + bean.getFileA().getName());
        bean.publish("File B: " + bean.getFileB().getName());
        bean.publish("");
        bean.publish("Format: " + clip.getFormat());
        bean.publish("");
        bean.publish("Transition Module:     " + clip.getTransitioner().getName());
        bean.publish("Transition Parameters: " + clip.getTransitioner().getParameters());
        bean.publish("Transition Length:     " + bean.getTransitionLength() + " ms");
        bean.publish("");
    }

    public void resetTest() {
        bean.setLog("");
        bean.setModifiable(true);
        bean.setReadyForTesting(true);
        bean.setNumberOfRounds(16);
        bean.setTransitionLength(80);
    }

    public void play() {
        clip.start();
    }

    public void pause() {
        clip.stop();
    }

    public void stop() {
        clip.stop();
        clip.setFramePosition(0);
        clip.flush();
    }

    public final void setMillisecondPosition(int position) {
        if (!clip.isActive()) {
            clip.setMicrosecondPosition(position * 1000l);
            clip.flush();
        }
    }

    public int getMillisecondPosition() {
        if (clip != null && clip.isOpen())
            return (int) (clip.getMicrosecondPosition() / 1000);
        else
            return 0;
    }

    public ABXBean getBean() {
        return bean;
    }

    public void setBean(ABXBean bean) {
        this.bean = bean;
    }
}
